import cv2.face
import numpy as np
import os

recognizer = cv2.face.LBPHFaceRecognizer_create()
# 加载识别器模型
recognizer.read("C:/Users/shouw/Desktop/tmp/trainer/trainer.yml")
faceCascade = cv2.CascadeClassifier('D:/facere/venv/Lib/site-packages/cv2/data/haarcascade_frontalface_default.xml')

cap = cv2.VideoCapture(0)
cap.set(3,640)
cap.set(4,480)

while cap.isOpened():
    ret,img = cap.read()
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    faces = faceCascade.detectMultiScale(gray,scaleFactor=1.05,minNeighbors=5)

    for(x,y,w,h) in faces:
        cv2.rectangle(img,(x,y),(x+w,y+h),(255,255,255),2)
        roi = cv2.resize(gray[y:y+h,x:x+w],(92,112))

        # 人脸检测，返回的id和confidence是标签和置信度
        id,confidence = recognizer.predict(roi)

        # 置信度评分用来衡量所识别人脸与原模型的差距，0表示完全匹配
        if(confidence < 100):
            confidence = "{0}%".format(round(100 - confidence))
        else:
            id = "unknown"
            confidence = "{0}%".format(round(100-confidence))
        cv2.putText(img,"person:" + str(id), (x+5, y-5),cv2.FONT_HERSHEY_SIMPLEX,1,(255,255,255),2)
        cv2.putText(img,str(confidence), (x+5,y+h-5),cv2.FONT_HERSHEY_SIMPLEX,1,(255,255,255),1)
    cv2.imshow('Recognizing face',img)

    if cv2.waitKey(10) & 0xff == 27:
            break

cap.release()
cv2.destroyAllWindows()